<template>
    <div>
        <BasicDialogVue :data="dialog" @close="onCloseDialog(formRef)">
            <template #content>
                <el-form ref="formRef" :model="formData" label-width="140px" status-icon>
                    <el-form-item label="菜单类型：">
                        <el-radio-group
                            v-model="formData.menuType"
                            @change="onChangeMenuType"
                            :disabled="dialog.type === 'edit' ? true : false"
                        >
                            <el-radio :label="item.value" v-for="item in menuType" :key="item.label">{{
                                item.label
                            }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="菜单名称：" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入菜单名称" clearable />
                    </el-form-item>
                    <el-form-item label="上级菜单：" prop="parentId">
                        <el-tree-select
                            v-model="formData.parentId"
                            :data="tableData"
                            :render-after-expand="false"
                            check-strictly
                            placeholder="请选择上级菜单"
                            node-key="id"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'subPermissions'
                            }"
                            style="width: 100%"
                            clearable
                        >
                        </el-tree-select>
                    </el-form-item>
                    <el-form-item label="路由地址：" prop="routePath" v-if="Number(formData.menuType) === 0">
                        <el-input v-model="formData.routePath" placeholder="请输入路由地址" clearable />
                    </el-form-item>
                    <el-form-item label="前端组件：" prop="component" v-if="Number(formData.menuType) === 0">
                        <el-input v-model="formData.component" placeholder="请输入前端组件" clearable />
                    </el-form-item>
                    <el-form-item label="前端组件名称：" prop="componentName" v-if="Number(formData.menuType) === 0">
                        <el-input v-model="formData.componentName" placeholder="请输入前端组件名称" clearable />
                    </el-form-item>
                    <el-form-item label="默认跳转地址：" v-if="Number(formData.menuType) === 0">
                        <el-input v-model="formData.defaultLink" placeholder="请输入默认跳转地址" clearable />
                    </el-form-item>
                    <el-form-item label="菜单图标：" v-if="Number(formData.menuType) === 0">
                        <el-popover placement="bottom" :width="394" trigger="click">
                            <template #reference>
                                <el-input v-model="formData.icon" placeholder="请选择菜单图标" clearable>
                                    <template #prefix>
                                        <component v-if="formData.icon" :is="formData.icon" />
                                    </template>
                                </el-input>
                            </template>
                            <div class="icon-list">
                                <div
                                    v-for="item in uStore.icons"
                                    :key="item"
                                    class="item"
                                    @click="formData.icon = item"
                                >
                                    <component :is="item" />
                                </div>
                            </div>
                        </el-popover>
                    </el-form-item>
                    <el-form-item label="排序：">
                        <el-input v-model="formData.sort" placeholder="请输入排序" clearable />
                    </el-form-item>
                    <el-form-item label="是否是路由菜单：" v-if="Number(formData.menuType) === 0">
                        <el-switch v-model="formData.isRoute" inline-prompt active-text="启用" inactive-text="禁用" />
                    </el-form-item>
                    <el-form-item label="接口编码：" v-if="Number(formData.menuType) !== 0">
                        <el-input v-model="formData.permsUrl" placeholder="请输入接口编码" clearable />
                    </el-form-item>

                    <div style="display: flex; justify-content: center; margin: 10px">
                        <el-button type="primary" @click="submitForm(formRef)"> 确定 </el-button>
                        <el-button @click="onCloseDialog(formRef)">取消</el-button>
                    </div>
                </el-form>
            </template>
        </BasicDialogVue>
    </div>
</template>
<script setup lang="ts">
import BasicDialogVue from '@/components/baseDialog/Index.vue'
import { ref, reactive, watchEffect } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { DICT_DATA } from '@/utils/dict-data'
import { createMenu, menuOperate, updateMenu } from '@/apis/system/menu'
import { userStore } from '@/store/user.store'

const props = defineProps(['data', 'tableData'])
const emit = defineEmits(['close'])

const uStore = userStore()

const formRef = ref()
const dialog = reactive({
    visible: false,
    title: '新增菜单',
    width: '600px',
    id: '',
    type: 'create'
})

//菜单类型
const menuType = reactive<{ label: string; value: string }[]>(DICT_DATA.get('menuType'))

//是否提交
let resubmit = false

const formData = reactive({
    id: '',
    menuType: '0',
    name: '',
    parentId: '',
    routePath: '',
    component: '',
    componentName: '',
    defaultLink: '',
    icon: '',
    sort: '',
    isRoute: true,
    permsUrl: '',
    url: ''
})

//校验输入
const rules = reactive({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    path: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }],
    component: [{ required: true, message: '请输入组件地址', trigger: 'blur' }]
})

watchEffect(() => {
    dialog.visible = props.data.visible
    if (props.data.visible) {
        resetFormData()
        dialog.id = props.data.id
        formData.id = props.data.id
        formData.parentId = props.data.parentId
        formData.menuType = '0'
    }
    if (props.data.type === 'edit') {
        dialog.title = '编辑菜单'
        dialog.type = 'edit'
        formData.menuType = props.data.menuType + ''
        formData.name = props.data.name
        formData.parentId = props.data.parentId
        formData.routePath = props.data.routePath
        formData.component = props.data.component
        formData.componentName = props.data.componentName
        formData.defaultLink = props.data.defaultLink
        formData.icon = props.data.icon
        formData.sort = props.data.sort
        formData.isRoute = props.data.isRoute
        formData.permsUrl = props.data.permsUrl
    } else if (props.data.type === 'create') {
        dialog.title = '新增菜单'
        dialog.type = 'create'
    }
})

//监听选择的菜单类型
const onChangeMenuType = (res: any) => {
    //重置数据
    formRef.value.resetFields()
    resetFormData()
}

//重置数据
function resetFormData() {
    formData.name = ''
    formData.parentId = props.data.parentId
    formData.routePath = ''
    formData.component = ''
    formData.componentName = ''
    formData.defaultLink = ''
    formData.icon = ''
    formData.sort = ''
    formData.isRoute = true
    formData.permsUrl = ''
}

//监听关闭
const onCloseDialog = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    emit('close')
}
//监听提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', formData)
            if (resubmit) {
                return
            }
            // resubmit = true
            const data: menuOperate = {
                component: formData.component,
                componentName: formData.componentName,
                icon: formData.icon,
                isRoute: Number(formData.isRoute), //是否路由菜单: 0:不是 1:是（默认值1）（前端）
                name: formData.name,
                parentId: formData.parentId,
                permsUrl: formData.permsUrl,
                redirect: formData.defaultLink,
                sortNo: Number(formData.sort),
                type: Number(formData.menuType), //类型(0菜单，1按钮，2接口)
                routePath: formData.routePath
            }
            if (dialog.type === 'create') {
                createMenu(data).then(res => {
                    if (Number(res.data.code) === 200) {
                        ElMessage.success('创建成功')
                        onCloseDialog(formEl)
                    }
                })
            } else if (dialog.type === 'edit') {
                data.id = formData.id
                updateMenu(data).then(res => {
                    if (Number(res.data.code) === 200) {
                        ElMessage.success('修改成功')
                        onCloseDialog(formEl)
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style scoped lang="scss">
.btn {
    display: flex;
    justify-content: center;
    margin: 40px 0 16px 0;
}
.icon-list {
    display: flex;
    flex-wrap: wrap;
    border-left: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    max-height: 300px;
    overflow-y: auto;
    .item {
        width: 40px;
        height: 40px;
        border-top: 1px solid #dcdfe6;
        border-right: 1px solid #dcdfe6;
        box-sizing: border-box;
        padding: 8px;
        &:hover {
            background-color: rgb(245, 255, 255);
            cursor: pointer;
        }
    }
}
</style>
